package cn.mumzone.pos.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.mumzone.basic.base.BaseActivity;
import cn.mumzone.basic.loading.button.LoadingButton;
import cn.mumzone.basic.util.AppDateUtil;
import cn.mumzone.basic.util.DisplayUtil;
import cn.mumzone.basic.util.ListUtil;
import cn.mumzone.basic.util.PosToast;
import cn.mumzone.basic.util.StringUtils;
import cn.mumzone.basic.util.ToastUtil;
import cn.mumzone.pos.AppConstants;
import cn.mumzone.pos.R;
import cn.mumzone.pos.model.LevelListEntity;
import cn.mumzone.pos.model.MemberEntity;
import cn.mumzone.pos.presenter.MemberAddOrModifyPresenter;
import cn.mumzone.pos.presenter.contract.MemberAddOrModifyContract;
import cn.mumzone.pos.ui.widgets.FlowLayout;

public class ACT_AddOrModifyMember extends BaseActivity<MemberAddOrModifyPresenter> implements MemberAddOrModifyContract.View {

    @BindView(R.id.tv_title)
    TextView tvTitle;

    @BindView(R.id.et_member_phone)
    EditText etMemberPhone;

    @BindView(R.id.et_member_name)
    EditText etMemberName;

    @BindView(R.id.rg_gender)
    RadioGroup rgGender;

    @BindView(R.id.fl_member_level)
    FlowLayout flMemberLevel;

    @BindView(R.id.fl_baby_relation)
    FlowLayout flBabyRelation;

    @BindView(R.id.rg_pregnant)
    RadioGroup rgPregnant;

    @BindView(R.id.et_select_member_birthday)
    EditText etSelectMemberBirthday;
    @BindView(R.id.et_select_confinement_date)
    EditText etSelectConfinementDate;
    @BindView(R.id.rl_confinement_date)
    RelativeLayout rlConfinementDate;
    @BindView(R.id.lb_save)
    LoadingButton lbSave;

    @BindView(R.id.tv_member_phone_title)
    TextView tvMemberPhoneTitle;

    @BindView(R.id.tv_member_name_title)
    TextView tvMemberNameTitle;

    @BindView(R.id.tv_member_gender_title)
    TextView tvMemberGenderTitle;

    @BindView(R.id.tv_member_level_title)
    TextView tvMemberLevelTitle;

    @BindView(R.id.tv_confinement_date_title)
    TextView tvConfinementDateTitle;


    private String selectedGender = "0";
    private MemberEntity memberEntity;
    private String memberId;

    private String momStatus = " ";

    private TimePickerView birthdayPickerView;
    private TimePickerView confinementDatePickerView;

    @Override
    protected void getBundleExtras(Bundle extras) {
        super.getBundleExtras(extras);
        memberEntity = (MemberEntity) extras.getSerializable("member");
        if (memberEntity == null) {
            memberId = "";
        } else {
            memberId = memberEntity.getId();
        }
    }

    @Override
    protected void initEventAndData() {

        SpannableString memberPhoneTitle = new SpannableString("* 手机号");
        memberPhoneTitle.setSpan(new ForegroundColorSpan(Color.RED), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        tvMemberPhoneTitle.setText(memberPhoneTitle);

        SpannableString memberNameTitle = new SpannableString("* 姓名");
        memberNameTitle.setSpan(new ForegroundColorSpan(Color.RED), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        tvMemberNameTitle.setText(memberNameTitle);

        SpannableString memberGenderTitle = new SpannableString("* 性别");
        memberGenderTitle.setSpan(new ForegroundColorSpan(Color.RED), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        tvMemberGenderTitle.setText(memberGenderTitle);

        SpannableString memberLevelTitle = new SpannableString("* 会员等级");
        memberLevelTitle.setSpan(new ForegroundColorSpan(Color.RED), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        tvMemberLevelTitle.setText(memberLevelTitle);

        SpannableString confinementDateTitle = new SpannableString("* 预产期");
        confinementDateTitle.setSpan(new ForegroundColorSpan(Color.RED), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        tvConfinementDateTitle.setText(confinementDateTitle);


        etMemberPhone.setFilters(new InputFilter[]{new InputFilter.LengthFilter(11)});
        etMemberName.setFilters(new InputFilter[]{new InputFilter.LengthFilter(10)});

        List<LevelListEntity> levelList = JSON.parseArray(AppConstants.TEMP_MEMBER_LEVEL, LevelListEntity.class);

        List<String> babyRelations = new ArrayList<>();
        babyRelations.add("爸爸");
        babyRelations.add("妈妈");
        babyRelations.add("叔叔");
        babyRelations.add("阿姨");
        babyRelations.add("爷爷");
        babyRelations.add("奶奶");
        babyRelations.add("外公");
        babyRelations.add("外婆");

        initBirthdayPickerDialog();

        initConfinementDatePickerDialog();

        if (memberEntity == null) {//新增
            tvTitle.setText("新增会员信息");

            lbSave.setText("确认添加会员");

            if (!ListUtil.isListEmpty(levelList)) {
                String defaultLevel = "";
                for (int index = 0; index < levelList.size(); index++) {
                    LevelListEntity level = levelList.get(index);
                    if ("1".equals(level.getLevelType())) {
                        defaultLevel = level.getFlowName();
                        break;
                    }
                    if (index == levelList.size() - 1 && StringUtils.isEmpty(defaultLevel)) {
                        defaultLevel = level.getFlowName();
                        break;
                    }
                }
                flMemberLevel.checkDefault(defaultLevel);
            }
//            flBabyRelation.checkDefault(babyRelations.get(0));
        } else {//修改
            tvTitle.setText("修改会员信息");

            lbSave.setText("保存");
            etMemberPhone.setText(memberEntity.getPhone());
            etMemberPhone.setEnabled(false);
            etMemberPhone.setTextColor(getResources().getColor(R.color.content_text_color));

            etMemberName.setText(memberEntity.getName());

            if (memberEntity.getGender() == 0) {
                rgGender.check(R.id.rb_gender_man);
            } else {
                rgGender.check(R.id.rb_gender_women);
            }

            if (!ListUtil.isListEmpty(levelList)) {
                flMemberLevel.checkDefault(memberEntity.getLevelName());
            }

            if (memberEntity.getCurrentState() == 1) {//"怀孕中"
                rgPregnant.check(R.id.rb_pregnant_status_pregnant);
                rlConfinementDate.setVisibility(View.VISIBLE);
                etSelectConfinementDate.setText(AppDateUtil.getTimeStamp(memberEntity.getConfinementDate(),
                        AppDateUtil.YYYY_MM_DD));
            } else if (memberEntity.getCurrentState() == 2) {//已有宝宝
                rgPregnant.check(R.id.rb_pregnant_status_have_baby);
            } else if (memberEntity.getCurrentState() == 3) {//备孕中
                rgPregnant.check(R.id.rb_pregnant_status_prepare);
            }

            etSelectMemberBirthday.setText(StringUtils.isEmpty(memberEntity.getBirthday()) ? "" :
                    AppDateUtil.getTimeStamp(Long.valueOf(StringUtils.get(memberEntity.getBirthday(), "0")), AppDateUtil.YYYY_MM_DD));

            for (int i = 0; i < (memberEntity.getParamters() == null ? 0 : memberEntity.getParamters().size()); i++) {
                if (memberEntity.getParamters().get(i).getName().equals("与宝宝关系")) {
                    flBabyRelation.checkDefault(memberEntity.getParamters().get(i).getValue());
                }
            }
        }

        if (!ListUtil.isListEmpty(levelList)) {
            flMemberLevel.update(levelList);
        }
        flBabyRelation.updateStr(babyRelations);

        rgGender.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.rb_gender_man:
                        selectedGender = "0";
                        break;
                    case R.id.rb_gender_women:
                        selectedGender = "1";
                        break;
                }
            }
        });

        rgPregnant.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.rb_pregnant_status_prepare:
                        rlConfinementDate.setVisibility(View.GONE);
                        etSelectConfinementDate.setText("");
                        momStatus = "备孕中";
                        break;
                    case R.id.rb_pregnant_status_pregnant:
                        rlConfinementDate.setVisibility(View.VISIBLE);
                        momStatus = "怀孕中";
                        break;
                    case R.id.rb_pregnant_status_have_baby:
                        rlConfinementDate.setVisibility(View.GONE);
                        etSelectConfinementDate.setText("");
                        momStatus = "已有宝宝";
                        break;
                }
            }
        });


        etMemberName.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    etMemberName.post(new Runnable() {
                        @Override
                        public void run() {
                            etMemberName.setSelection(etMemberName.getText().length());
                        }
                    });
                }
            }
        });

        etMemberPhone.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    etMemberPhone.post(new Runnable() {
                        @Override
                        public void run() {
                            etMemberPhone.setSelection(etMemberPhone.getText().length());
                        }
                    });
                }
            }
        });
    }

    /**
     * 初始化预产期时间选择器
     */
    private void initConfinementDatePickerDialog() {
        Calendar nowDate = Calendar.getInstance();
        Calendar startDate = Calendar.getInstance();
        startDate.set(nowDate.get(Calendar.YEAR), nowDate.get(Calendar.MONTH), nowDate.get(Calendar.DATE));
        Calendar endDate = Calendar.getInstance();
        endDate.set(nowDate.get(Calendar.YEAR) + 1, nowDate.get(Calendar.MONTH), nowDate.get(Calendar.DATE));
        confinementDatePickerView = new TimePickerBuilder(mContext, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                confinementDatePickerView.dismiss();
                etSelectConfinementDate.setText(AppDateUtil.getDateToString(date.getTime(), AppDateUtil.YYYY_MM_DD));
            }
        }).isDialog(true).isCyclic(false).setOutSideCancelable(true)
                .setType(new boolean[]{true, true, true, false, false, false})
                .setDate(nowDate)
                .setRangDate(startDate, endDate)
                .build();
        confinementDatePickerView.getDialog().getWindow().setLayout(DisplayUtil.dip2px(mContext, 500),
                WindowManager.LayoutParams.WRAP_CONTENT);
    }

    /**
     * 初始化生日时间选择器
     */
    private void initBirthdayPickerDialog() {
        Calendar nowDate = Calendar.getInstance();
        Calendar startDate = Calendar.getInstance();
        startDate.set(1900, 0, 1);
        Calendar endDate = Calendar.getInstance();

        birthdayPickerView = new TimePickerBuilder(mContext, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                birthdayPickerView.dismiss();
                etSelectMemberBirthday.setText(AppDateUtil.getDateToString(date.getTime(), AppDateUtil.YYYY_MM_DD));
            }
        }).isDialog(true).isCyclic(false).setOutSideCancelable(true)
                .setType(new boolean[]{true, true, true, false, false, false})
                .setDate(nowDate)
                .setRangDate(startDate, endDate)
                .build();
        birthdayPickerView.getDialog().getWindow().setLayout(DisplayUtil.dip2px(mContext, 500),
                WindowManager.LayoutParams.WRAP_CONTENT);
    }

    @Override
    protected int getLayout() {
        return R.layout.act_add_or_modify_member;
    }


    @OnClick(value = {R.id.iv_back, R.id.et_select_confinement_date, R.id.et_select_member_birthday, R.id.lb_save})
    public void toggleEvent(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.et_select_confinement_date:
                confinementDatePickerView.getDialog().show();
                break;
            case R.id.et_select_member_birthday:
                birthdayPickerView.getDialog().show();
                break;
            case R.id.lb_save:
                if (!mPresenter.isInputLegal(etMemberName.getText().toString(), etMemberPhone.getText().toString(),
                        flMemberLevel.getCheckedString())) {
                    return;
                }

                if (rgPregnant.getCheckedRadioButtonId() == R.id.rb_pregnant_status_pregnant) {
                    if (TextUtils.isEmpty(etSelectConfinementDate.getText().toString())) {
                        ToastUtil.makeText(this, "请选择预产期", false);
                        return;
                    }
                }
                LevelListEntity listEntity = (LevelListEntity) flMemberLevel.getCheckedEntity();
                mPresenter.createOrModifyMemberInfo(etMemberName.getText().toString(),
                        etMemberPhone.getText().toString(), selectedGender,
                        listEntity.getId(), etSelectMemberBirthday.getText().toString(),
                        flBabyRelation.getCheckedString(),
                        momStatus, etSelectConfinementDate.getText().toString(), memberId);
                if (memberEntity == null) {
                    lbSave.startLoading("确认添加会员");
                } else {
                    lbSave.startLoading("保存");
                }
                break;
        }
    }

    @Override
    public void onCreateOrModifyMemberInfoSuccess(MemberEntity memberEntity, boolean isAppend) {
        if (isAppend) {
            PosToast.INSTANCE.makeToast(this, PosToast.ToastType.TOAST_TYPE_SQUARE,
                    PosToast.ToastSquareLevel.ALERT_SUCCESS_SQUARE, "添加成功", false);
            Intent intent = new Intent(this, ACT_MemberDetail.class);
            Bundle bundle = new Bundle();
            bundle.putString("memberPhone", memberEntity.getPhone());
            bundle.putString("memberId", memberEntity.getId());
            intent.putExtras(bundle);
            startActivity(intent);
            finish();
        } else {
            PosToast.INSTANCE.makeCheckMarkToast(this, "已保存");
            Intent intent = new Intent();
            memberEntity.setMemberId(memberEntity.getId());
            intent.putExtra("memberEntity", memberEntity);
            setResult(Activity.RESULT_OK, intent);
            finish();
        }
    }

    @Override
    public void onCreateOrModifyMemberInfoFailed(boolean isAppend, String errorMsg) {
        if (isAppend) {
            PosToast.INSTANCE.makeToast(this, PosToast.ToastType.TOAST_TYPE_SQUARE,
                    PosToast.ToastSquareLevel.ALERT_FAIL_SQUARE, errorMsg, false);
        } else {
            PosToast.INSTANCE.makeCheckMarkToast(this, "保存失败");
        }

        if (memberEntity == null) {
            lbSave.stopLoading("确认添加会员");
        } else {
            lbSave.stopLoading("保存");
        }
    }
}
